'use strict';
const assert = require('assert');
const MIDDLEWARE_NAME_LOGER = 'loger';

const koaLog = require('homedo-koa-log');
const morgan = koaLog.morgan;

module.exports = app => {

    morgan.token('host', function (app) {
        let host = app.request.get('host');
        if (host) {
            return host;
        }
        return '-';
    });

    morgan.token('X-Forwarded-Host', function (app) {
        let xForwardedHost = app.request.get('X-Forwarded-Host');
        if (xForwardedHost) {
            return xForwardedHost;
        }
        return '-';
    });

    morgan.token('X-Forwarded-For', function (app) {
        let xForwardedFor = app.request.get('X-Forwarded-For');
        if (xForwardedFor) {
            return xForwardedFor;
        }
        return '-';
    });

    const index = app.config.appMiddleware.indexOf(MIDDLEWARE_NAME_LOGER);
    assert.equal(index, -1, `Duplication of middleware name found: ${MIDDLEWARE_NAME_LOGER}. Rename your middleware other than "${MIDDLEWARE_NAME_LOGER}" please.`);
    app.config.coreMiddleware.unshift(MIDDLEWARE_NAME_LOGER);
};
